#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
简单测试脚本 - 不依赖外部包
测试基础代码逻辑
"""

def test_chat_return_format():
    """测试chat方法的返回格式"""
    print("🧪 测试chat方法返回格式...")
    
    # 模拟chat方法的不同返回情况
    test_cases = [
        ("正常情况", ("这是回答", [{"file_name": "test.py"}])),
        ("空源文件", ("这是回答", [])),
        ("空回答", ("", [])),
        ("None情况", None),
        ("单一值", "只返回字符串"),
        ("空元组", ()),
        ("单元组", ("只有一个值",))
    ]
    
    for case_name, return_value in test_cases:
        print(f"\n测试案例: {case_name}")
        print(f"返回值: {return_value}")
        print(f"返回类型: {type(return_value)}")
        
        try:
            if return_value is None:
                print("❌ 返回None会导致解包错误")
            elif isinstance(return_value, tuple):
                if len(return_value) == 2:
                    response, sources = return_value
                    print(f"✅ 解包成功: response='{response}', sources={len(sources) if sources else 0}个")
                elif len(return_value) == 0:
                    print("❌ 空元组会导致解包错误")
                elif len(return_value) == 1:
                    print("❌ 单元组会导致解包错误")
                else:
                    print(f"❌ 元组长度{len(return_value)}不匹配")
            else:
                print("❌ 非元组类型会导致解包错误")
                
        except ValueError as e:
            print(f"❌ 解包错误: {e}")


def test_function_definition():
    """测试函数定义的问题"""
    print("\n🔍 分析可能的函数定义问题...")
    
    def normal_chat(message):
        """正常的chat函数"""
        return "回答", ["源文件"]
    
    def problematic_chat_1(message):
        """问题函数1：有时不返回值"""
        if len(message) > 10:
            return "回答", ["源文件"]
        # 这里没有return语句，会返回None
    
    def problematic_chat_2(message):
        """问题函数2：条件返回不匹配"""
        if "special" in message:
            return "特殊回答"  # 只返回一个值
        return "普通回答", ["源文件"]
    
    def problematic_chat_3(message):
        """问题函数3：异常处理不当"""
        try:
            # 一些可能失败的操作
            if "error" in message:
                raise Exception("模拟错误")
            return "回答", ["源文件"]
        except:
            return  # 空return，返回None
    
    # 测试这些函数
    functions = [
        ("normal_chat", normal_chat),
        ("problematic_chat_1", problematic_chat_1),
        ("problematic_chat_2", problematic_chat_2),
        ("problematic_chat_3", problematic_chat_3)
    ]
    
    test_messages = ["hello", "this is a very long message", "special message", "error message"]
    
    for func_name, func in functions:
        print(f"\n测试函数: {func_name}")
        
        for msg in test_messages:
            try:
                result = func(msg)
                print(f"  '{msg}': {result} (类型: {type(result)})")
                
                if result is not None and isinstance(result, tuple) and len(result) == 2:
                    response, sources = result
                    print(f"    ✅ 解包成功")
                else:
                    print(f"    ❌ 解包会失败")
                    
            except Exception as e:
                print(f"  '{msg}': 异常 {e}")


def main():
    """主测试函数"""
    print("🔧 RAG系统返回值格式分析")
    print("=" * 50)
    
    test_chat_return_format()
    test_function_definition()
    
    print("\n" + "=" * 50)
    print("💡 可能的解决方案:")
    print("1. 确保chat方法总是返回 (response, sources) 元组")
    print("2. 在异常处理中返回默认值而不是None")
    print("3. 检查所有代码路径都有正确的返回语句")
    print("4. 添加类型检查和调试日志")


if __name__ == "__main__":
    main()